﻿using Stee.CAP8.MessageBus.Interface.Models;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Stee.CAP8.MessageBus.Sagas.Core.Sagas
{
    public class InMemorySagaStorage : ISagaStorage
    {
        private static readonly ConcurrentDictionary<string, List<SagaDataProperty>> _storageList = new ConcurrentDictionary<string, List<SagaDataProperty>> ();

        public Task DeleteAsync(string id, SagaDataProperty sagaDataProperty)
        {
            throw new NotImplementedException();
        }

        public Task<List<SagaDataProperty>> FindAsync(string id)
        {
             _storageList.TryGetValue(id, out var values);
            return Task.FromResult(values);
        }

        public List<SagaDataProperty> Find(string id)
        {
            _storageList.TryGetValue(id, out var values);
            return values;
        }
        public void Insert(string id, SagaDataProperty sagaDataProperty)
        {
            _storageList.TryGetValue(id, out var values);

            values ??= new List<SagaDataProperty>() { sagaDataProperty };
            values.Add(sagaDataProperty);
            _storageList.AddOrUpdate(id, values, (id, values) => {

                return values;
            });
        }

        public Task InsertAsync(string id, SagaDataProperty sagaDataProperty)
        {
            _storageList.TryGetValue(id, out var values);
            values ??= new List<SagaDataProperty>() { sagaDataProperty };
            _storageList.AddOrUpdate(id, values,(id,values)=> {

                return values;
            });
            return Task.CompletedTask;
        }
    }
}
